package tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpClient {
    //创建用于连接的Socket对象
    public Socket clientSocket=null;
    public TcpClient() throws IOException {
        //与指定服务器建立连接
        clientSocket=new Socket("127.0.0.1", 8000);
    }

    //长连接
    public void start() throws IOException {
        //先获取到输入输出流
        try(InputStream inputStream= clientSocket.getInputStream();
            OutputStream outputStream=clientSocket.getOutputStream()){
            Scanner scannerNet=new Scanner(inputStream);
            PrintWriter printWriter=new PrintWriter(outputStream);
            while (true){
                //输入请求
                System.out.println("输入请求:>");
                Scanner scanner=new Scanner(System.in);
                String request=scanner.next();

                //通过Socket的输入输出流将请求发给服务器和接收服务器的响应信息
                printWriter.write(request);
                //刷新缓存区
                printWriter.flush();
                //读取服务器端返回的数据
                String respon=scannerNet.next();
                System.out.printf("req: %s; resp: %s\n", request, respon);
            }
        } finally {
            clientSocket.close();
        }
    }

    public static void main(String[] args) throws IOException {
        //没有建立连接的话会在这里阻塞等待
        TcpClient tcpClient=new TcpClient();
        tcpClient.start();
    }
}
